#include <stdio.h>
#include <pthread.h>
#include <unistd.h> // usleep


/**
*   筷子作为临界资源, 使用互斥量来控制访问
*/

pthread_mutex_t kuai[5];           //
pthread_t ph[5];

typedef struct {
    char name;
    pthread_mutex_t *left;
    int left_name;
    pthread_mutex_t *right;
    int right_name;
}LL;

void* eat(void *args){
    LL *op = (LL*)args;
    while(1){
        printf("%c: ",op->name);
        pthread_mutex_lock(op->left);
        printf(" left: %d", op->name, op->left_name);
        pthread_mutex_lock(op->right);
        printf(" right: %d eat()\n",op->right_name);
        usleep(500 * 1000);
        pthread_mutex_unlock(op->left);
        pthread_mutex_unlock(op->right);
    }

}
int main(int argc, char *argv[]){
    setbuf(stdin, NULL);

    for(int i =0; i < sizeof(kuai); i++){
        pthread_mutex_init(kuai + i, NULL);
    }


    LL a = {'A',&kuai[4],5, &kuai[0], 1};
    LL b = {'B',&kuai[0],1, &kuai[1], 2};
    LL c = {'C',&kuai[1],2, &kuai[2], 3};
    LL d = {'D',&kuai[2],3, &kuai[3], 4};
    LL e = {'E',&kuai[3],4, &kuai[4], 5};



    pthread_create(&ph[2], NULL, eat, &c);
    pthread_create(&ph[3], NULL, eat, &d);
    pthread_create(&ph[4], NULL, eat, &e);

    pthread_create(&ph[0], NULL, eat, &a);
    pthread_create(&ph[1], NULL, eat, &b);



    for(int i =0; i < sizeof(kuai); i++){
        pthread_join(kuai[i], NULL);
    }
    for(int i =0; i < sizeof(kuai); i++){
        pthread_mutex_destroy(kuai + i);
    }

    return 0;
}
